package club.itstudio.itouc.jw

import club.itstudio.itouc.core.exception.ConnectFailure
import club.itstudio.itouc.entity.JwSession
import com.github.kittinunf.fuel.Fuel
import com.github.kittinunf.fuel.core.FuelError
import com.github.kittinunf.fuel.core.Parameters
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpMethod
import java.nio.charset.Charset
import com.github.kittinunf.result.Result
/**
 * @JwParams 教务系统请求参数
 * @param path: 路径
 * @param method: 方法
 * @param params: 参数
 * @param charset: 字符集
 */
data class JwParams(
        val path: String,
        val method: HttpMethod = HttpMethod.GET,
        val params: Parameters = emptyList(),
        val charset: Charset = charset("GBK")
)

/**
 * 解析响应返回值
 * Failure 抛异常
 * Success 返回结果
 */
fun parse(result: Result<String, FuelError>): String{
    return when (result) {
        is Result.Failure-> {
            throw ConnectFailure()
        }
        is Result.Success -> {
            result.get()
        }
    }
}

/**
 * @JwParams with 中缀方法
 * @param jwSession: 有效回话
 */
infix fun JwParams.with(jwSession: JwSession): String {
    val result = when(this.method) {
        HttpMethod.GET -> Fuel.get(this.path, this.params).header(
                HttpHeaders.COOKIE to jwSession ,
                HttpHeaders.REFERER to JwHost
        ).responseString(this.charset)
        HttpMethod.POST -> Fuel.post(this.path, this.params).header(
                HttpHeaders.COOKIE to jwSession,
                HttpHeaders.REFERER to JwHost
        ).responseString(this.charset)
        else -> Fuel.get(this.path, this.params).header(
                HttpHeaders.COOKIE to jwSession,
                HttpHeaders.REFERER to  JwHost
        ).responseString(this.charset)
    }
    return parse(result.third)
}

/**
 * get方法，不需要session
 */
fun JwParams.get(): String {
    val session = JwSession("", "", "", 0, "")
    return this with session
}
